package web.controller.user;

import common.consts.ContentType;
import common.validation.ValidationResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import service.ServiceResponse;
import service.WorkPreferenceService;
import web.Routes;
import web.controller.Base;
import web.req.PreferenceRequest;
import web.security.Protection;

/**
 * Created by aceyin on 15/7/6.
 */
@RestController
@RequestMapping(Routes.User.PREFERENCE)
public class Preference extends Base {

    private static final Logger logger = LoggerFactory.getLogger(Preference.class);

    @Autowired
    WorkPreferenceService workPreferenceService;

    @Protection
    @RequestMapping(method = RequestMethod.POST, produces = ContentType.JSON)
    public ServiceResponse save(@RequestBody PreferenceRequest request) {

        ValidationResult validate = request.validate();
        if (validate.isFailed()) {
            return fail(validate.getMessage());
        }

        long userId = getUserIdFromAuthHeader();

        return workPreferenceService.saveOrUpdateUserPreference(userId, request.getRealPreference());
    }

    @Protection
    @RequestMapping(method = RequestMethod.GET, produces = ContentType.JSON)
    public ServiceResponse get() {

        long userId = getUserIdFromAuthHeader();
        return workPreferenceService.getUserPreference(userId);
    }
}
